package com.chd.driversystem.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chd.driversystem.R;
import com.chd.driversystem.activity.msgbean.NetMsg;
import com.chd.driversystem.adapter.RankingAdapter;
import com.chd.driversystem.domain.Evaluation;
import com.chd.driversystem.domain.Ranking;
import com.chd.driversystem.domain.User;
import com.chd.driversystem.gen.BeanServer;
import com.chd.driversystem.service.HttpService;
import com.chd.driversystem.util.network.tools.HttpConstants;
import com.chd.driversystem.util.tools.Constants;
import com.chd.driversystem.util.tools.LogUtil;
import com.chd.driversystem.util.tools.MyApplication;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import lib.kingja.switchbutton.SwitchMultiButton;

public class RankingActivity extends BaseActivity {
    public static final String TAG = "RankingActivity";
    private List<String> items = Arrays.asList("天排名", "周排名", "月排名");
    private List<Ranking> rankings;

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.smb_switchrange)
    SwitchMultiButton smbSwitchRange;

    @BindView(R.id.tv_ranking)
    TextView tvRanking;

    @BindView(R.id.tv_score)
    TextView tvScore;

    @BindView(R.id.civ_avator)
    CircleImageView civAvator;

    @BindView(R.id.rv_rankinglist)
    RecyclerView rvRankingList;

    //列表适配器
    private RankingAdapter adapter;

    //排名类型
    private Integer rankingType;

    @BindView(R.id.rl_usertab)
    RelativeLayout rlUsertab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ranking);
        ButterKnife.bind(this);

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        params = new HashMap<String, Object>();
        rankingType = Evaluation.WEEK_EVALUATION;
        params.put(Constants.EXTRA_PARAM1, rankingType);

        toolbar.setTitle("排名");
        toolbar.setContentInsetStartWithNavigation(450);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        initView();

        LogUtil.d(TAG, "User = " + MyApplication.getUser().toString());
    }

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, RankingActivity.class);
        context.startActivity(intent);
    }

    public void initView() {
        //是否隐藏用户栏
        if (MyApplication.getUser().getIsManager()) {
            rlUsertab.setVisibility(View.GONE);
        }

        //切换按钮
        assert smbSwitchRange != null;
        smbSwitchRange.setText(items).setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
            @Override
            public void onSwitch(int position, String tabText) {
                params = new HashMap<>();
                switch (position) {
                    case 0:
                        rankingType = Evaluation.DAY_EVALUATION;
                        params.put(Constants.EXTRA_PARAM1, rankingType);
                        systemBindler.setParams(params);
                        break;
                    case 1:
                        rankingType = Evaluation.WEEK_EVALUATION;
                        params.put(Constants.EXTRA_PARAM1, rankingType);
                        systemBindler.setParams(params);
                        break;
                    case 2:
                        rankingType = Evaluation.MONTH_EVALUATION;
                        params.put(Constants.EXTRA_PARAM1, rankingType);
                        systemBindler.setParams(params);
                        break;
                    default:
                        break;
                }
                systemBindler.refreshNetData();
                EventBus.getDefault().post(new NetMsg(NetMsg.BACKGROUND, HttpConstants.ACTION_EVALUATIONBYUSERLIST
                    ,HttpConstants.RESULT_OK,null,1,1));
                //refreshRanking();
            }
        });
        //排名初始化和刷新
        initRankingView();
    }

    private void initRankingView() {
        if (rankings == null) {
            rankings = new ArrayList<>();
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        rvRankingList.setLayoutManager(layoutManager);
        adapter = new RankingAdapter(this, rankings);
        rvRankingList.setAdapter(adapter);

        EventBus.getDefault().post(new NetMsg(NetMsg.BACKGROUND, Constants.ACTION_INIT));
    }

    /**
     * 刷新排名信息
     * 需在后天运行
     */
    private Long refreshRanking() {
        LogUtil.d(TAG, "refreshRanking() called");
        Long count = 0L;
        List<User> users = BeanServer.getInstance().getDriverUsers();
        for (User user : users) {
            Evaluation evaluation = BeanServer.getInstance().getLastEvaluationByType(user.getId(), rankingType);
            Ranking ranking = BeanServer.getInstance().getRankingByUserId(user.getId());
            if (evaluation!=null) {
                if (ranking != null) {
                    if (ranking.getScore() != evaluation.getTScore()) {
                        ranking.setScore(evaluation.getTScore());
                        if (BeanServer.getInstance().saveRanking(ranking) > 0) {
                            count++;
                        }
                    }
                } else {
                    ranking = new Ranking(
                            null,
                            user.getId(),
                            null,
                            user.getName(),
                            evaluation.getTScore()
                    );
                    if (BeanServer.getInstance().saveRanking(ranking) > 0) {
                        count++;
                    }
                }
            }
        }
        if (count > 0) {
            List<Ranking> rankinglist = BeanServer.getInstance().getRankings();
            rankings.clear();
            rankings.addAll(rankinglist);
            LogUtil.d(TAG, "ranking size=" + rankinglist.size());
            Log.d(TAG, "refreshRanking: rankings:="+rankings);
            Log.d(TAG, "refreshRanking: rankinglist:="+rankinglist);
        }
        return count;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add_driver:

                break;
            case android.R.id.home:
                finish();
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (!MyApplication.getUser().getIsManager()) {
            HttpService.startServiceUserList(
                    MyApplication.getContext(),
                    MyApplication.getUser().getManagerId()
            );
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    public Integer getRankingType() {
        return rankingType;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshList(NetMsg netMsg) {
        if (netMsg.getType() == NetMsg.MAIN) {
            LogUtil.d(TAG, "receiverNetMsg() called with: netMsg = [" + netMsg + "]");
            switch (netMsg.getTAG()) {
                case HttpConstants.ACTION_EVALUATIONBYUSERLIST:
                    adapter.notifyDataSetChanged();
                    if (!MyApplication.getUser().getIsManager()) {
                        Ranking ranking = BeanServer.getInstance().getRankingByUserId(MyApplication.getUser().getId());
                        int rankingNum = rankings.indexOf(ranking);
                        tvRanking.setText("第" + (rankingNum + 1) + "名");
                        tvScore.setText(ranking.getScore() + "分");
                    }
                    break;
                case Constants.ACTION_INIT:
                    adapter.notifyDataSetChanged();
                    if (!MyApplication.getUser().getIsManager()) {
                        Ranking ranking = BeanServer.getInstance().getRankingByUserId(MyApplication.getUser().getId());
                        int rankingNum = rankings.indexOf(ranking);
                        tvRanking.setText("第" + (rankingNum + 1) + "名");
                        tvScore.setText(ranking.getScore() + "分");
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void receiverNetMsg(NetMsg netMsg) {
        if (netMsg.getType() == NetMsg.BACKGROUND) {
            LogUtil.d(TAG, "receiverNetMsg() called with: netMsg = [" + netMsg + "]");
            switch (netMsg.getTAG()) {
                case HttpConstants.ACTION_EVALUATIONBYUSERLIST:
                    if (netMsg.getRESULT().equals(HttpConstants.RESULT_OK)) {
                        if (netMsg.getCount() > 0) {
                            LogUtil.d(TAG, "onReceive() count = " + netMsg.getCount());
                            Long count = refreshRanking();
                            if (count>0) {
                                netMsg.setType(NetMsg.MAIN);
                            }
                            Log.d(TAG, "receiverNetMsg: count="+count);
                        }
                    } else {
                        //提示错误信息
                    }
                    break;
                case HttpConstants.ACTION_USERLIST:
                    if (netMsg.getRESULT().equals(HttpConstants.RESULT_OK)) {
                        if (netMsg.getCount() > 0) {
                            systemBindler.refreshNetData();
                        }
                    }
                    break;
                case Constants.ACTION_INIT:
                    List<Ranking> rankinglist = BeanServer.getInstance().getRankings();
                    rankings.clear();
                    rankings.addAll(rankinglist);
                    Log.d(TAG, "receiverNetMsg: rankinglist:="+rankings);
                    netMsg.setType(NetMsg.MAIN);
                    break;
                default:
                    break;
            }
        }
    }
}
